package com.szm.hibbonserver.webui;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.szm.hibbonserver.entity.Product;
import com.szm.hibbonserver.entity.User;
import com.szm.hibbonserver.entity.UserProduct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class UserProductController {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getuserproducthibbon")
    public UserProduct getUserProduct() {
        UserProduct userProduct = new UserProduct();
        userProduct.setUser(getUser());
        userProduct.setProduct(getProduct());
        return userProduct;
    }

    public UserProduct getUserProductFallback() {
        UserProduct userProduct = new UserProduct();
        userProduct.setErrorMessage("Hystrix开启成功！");
        return userProduct;
    }

    @HystrixCommand(fallbackMethod = "getUserProductFallback", commandProperties = {
            //timeoutInMilliseconds 使用线程隔离时，调用超时时间
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    private User getUser() {
        User user = restTemplate.getForObject("http://userserver/test", User.class);
        return user;
    }

    @HystrixCommand(fallbackMethod = "getUserProductFallback", commandProperties = {
            //timeoutInMilliseconds 使用线程隔离时，调用超时时间
            @HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "3000")
    })
    private Product getProduct() {
        Product product = restTemplate.getForObject("http://productserver/getproduct", Product.class);
        return product;
    }

}
